<?php
/**
 * 支付接口返回调用
 */
class Controller_Callback extends Controller_Abstract
{

	function actionPay()
	{
		$pay_type = ucfirst(trim($this->_context->p_t));
		$class_name = 'Helper_Payment_'.$pay_type;
		if (class_exists($class_name)) {
			// 支付方式类存在
			$payment = new $class_name();
			if ($payment->callback())
			{
				// 回调成功
				$back_order = $payment->back_order;
				$order = Orders::find('orderid = ?',$back_order['orderId'])->getOne();
				if ($order->id())
				{
					$url = url('pay/Dispatch',array('oid'=>$order->orderid),NULL,array('base_uri'=>'http://'.$_SERVER['HTTP_HOST']));
					$conn = QDB::getConn();
					// 存在订单
					switch ($order->orderstatus)
					{
						case 1:// 未支付,可以处理
							$conn->startTrans();
							try {
								// 修改订单状态
								$order->changeProps(array('orderstatus'=>2));
								$order->save();
								$conn->completeTrans();
							}catch (Exception $e){
								$conn->completeTrans(false);
								QLog::log('订单号:'.$order->orderid.' | '.$e->getMessage(), QLog::ERR);
								return $this->_redirectMessage('出错啦!', '订单处理错误!',$url);
							}
						case 2:// 已经支付,等待跳转发货
						case 0:// 成功
						case 3:// 已经发货
							return $this->_redirect($url);
							break;
						case 999:// 订单取消
						default:
							return $this->_redirectMessage('出错啦!', '订单已经取消!',$url);
							break;
					}
				}else{
					// 不存在订单
					return $this->_redirectMessage('出错啦!', '订单信息不存在!', url('default'));
				}
			}else{
				// 回调验证失败
					return $this->_redirectMessage('出错啦!', '订单信息被篡改!', url('default'));
			}
		}else{
			return $this->_redirect(url('default'));
		}
		exit;
	}
}